import axios from "axios"
import router from '../router/index'
import { ElMessage } from 'element-plus'
import cache from '../utils/cache'
import util from '../utils/util'

const api = axios.create({
  baseURL: '/api'
})
api.interceptors.request.use(request => {
  const user = cache.getObject(cache.keys.loginUser)
  if (user && user.token) {
    request.headers.Token = user.token
  }
  request.data = request.data || {}
  return request
})
let P000002 = false
let P000003 = false
api.interceptors.response.use(res => {
  if (res.status != 200 || !res.data) {
    ElMessage.error(JSON.stringify(res))
    throw res
  }
  if (res.data && res.data instanceof Blob && res.data.type == 'application/json') {
    util.readBlobAsJson(res.data).then(jsonData => {
      if (jsonData.code == 'P000001') {// 参数错误
        ElMessage.error(jsonData.message || util.language('参数错误', 'Parameter error'))
        return
      }
      if (jsonData.code == 'P000002') {// 登录失效
        cache.setObject(cache.keys.loginUser, null)
        if (P000002 == false) {
          P000002 = true
          ElMessage.error(util.language('未登录或已过期，请重新登录', 'Not logged in or expired, please login again'))
          router.push('/login')
          setTimeout(() => {
            P000002 = false
          }, 1000)
        }
        return
      }
      if (jsonData.code == 'P000003') {// 无权限
        if (P000003 == false) {
          P000003 = true
          ElMessage.error(util.language('无权限', 'No permission'))
          setTimeout(() => {
            P000003 = false
          }, 1000)
        }
        return
      }
      if (jsonData.code == 'S000001') {
        ElMessage.error('S000001 but not blob:' + JSON.stringify(jsonData))
        return
      }
      ElMessage.error(jsonData.message || JSON.stringify(jsonData))
    }).catch(err => {
      console.error(err)
      ElMessage.error('Load Blob as JSON failed')
    })
    throw res
  }
  return res
})
export default api